#include "cybertron/core/UtilRecordHelper.hpp"
#include "../PlatformHeader.hpp"
#include <iostream>
#include <cassert>
CYBERTRON_BEGIN

CybertronCoreAPI bool UtilRecordHelper::readOneReplayMsg(std::fstream &stream, Message &msg/*output*/)
{
	if (!stream.is_open() || stream.peek() == EOF)
		return false;
	msg.create(0, 0);
	unsigned char* pData = msg.getData();
	size_t len = msg.getLength();
	stream.read((char *)pData, len);
	std::uint16_t msgId = msg.parseMsgId();
	std::uint32_t msgBodyLength = msg.parseDataBodyLength();
	msg.create(msgId, msgBodyLength);
	stream.read((char *)msg.getDataBody(), msg.getDataBodyLength());
	return true;
}

CybertronCoreAPI bool UtilRecordHelper::readReplayTailMsg(std::fstream &stream, Message &msg/*output*/)
{
	if (!stream.is_open() || stream.peek() == EOF)
		return false;
	msg.create(0, 0);
	size_t bufPos = stream.tellg();
	unsigned char* pData = msg.getHeader();
	stream.seekg(0 - msg.getLength(), std::ios::end);
	stream.read((char *)pData, msg.getLength());
	std::uint16_t msgId = msg.parseMsgId();
	std::uint32_t msgBodyLength = msg.parseDataBodyLength();
	msg.create(msgId, msgBodyLength);
	stream.seekg(0 - msg.getLength(), std::ios::end);
	stream.read((char *)msg.getDataBody(), msg.getDataBodyLength());
	stream.seekg(bufPos, std::ios::beg);

	return true;
}

CybertronCoreAPI bool UtilRecordHelper::readOneReplayMsg(UtilRecordMemReader &reader, Message &msg/*output*/)
{
	msg.create(0, 0);
	unsigned char* pData = msg.getData();
	size_t len = msg.getLength();
	if (reader.read((char *)pData, len) != len) 
		return false;

	std::uint16_t msgId = msg.parseMsgId();
	std::uint32_t msgBodyLength = msg.parseDataBodyLength();
	msg.create(msgId, msgBodyLength);
	if (reader.read((char *)msg.getDataBody(), msg.getDataBodyLength()) != msg.getDataBodyLength())
		return false;

	return true;
}

CybertronCoreAPI bool UtilRecordHelper::readReplayTailMsg(UtilRecordMemReader &reader, Message &msg/*output*/)
{
	msg.create(0, 0);
	unsigned char* pData = msg.getHeader();
	size_t len = msg.getLength();
	if (reader.read_tail((char *)pData, len, len - 1) != len)
		return false;
	std::uint16_t msgId = msg.parseMsgId();
	std::uint32_t msgBodyLength = msg.parseDataBodyLength();
	msg.create(msgId, msgBodyLength);
	if (msg.getDataBodyLength() < 1)
	{
		return false;
	}

	if (reader.read_tail((char *)msg.getDataBody(), msg.getDataBodyLength() , msg.getLength() - 1) != msg.getDataBodyLength()) {
		return false;
	}
	return true;
}
CYBERTRON_END